package com.rabbitmq.origin.api;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.common.utils.RabbitMqUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author
 * @Describe 直连类型交换机, 该模式为路由模式。
 * 队列与交换机的绑定需要制定特定的路由key,只有当队列的路由key与发送消息的路由key完全一致时才能接收到生产者发送的消息
 * @date
 */
@Slf4j(topic = "RabbitMqProviderRouting")
public class RabbitMqProviderRouting {

    /**
     * 直连方式：队列绑定的交换机路由完全匹配才能接受发送的消息
     */
    public void publishDirect(String exchangeName, String routingKey, String msg) {
        Connection conn = null;
        Channel channel = null;
        try {
            // 获取连接
            conn = RabbitMqUtil.getConn();
            // 创建通道（通道可用于消息的发送和接收）
            channel = conn.createChannel();

            // 声明直连方式的交换机
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true);

            // 发布消息,消息发送到完全匹配路由的队列
            channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
        } catch (Exception e) {
            log.error("发布消息异常,", e);
        } finally {
            // log.info("[RabbitMqProviderRouting] publishDirect 关闭资源连接");
            RabbitMqUtil.close(conn, channel);
        }
    }
}
